using System;
using Foundry.Engine;
using System.Collections;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using System.Linq;
namespace Foundry.Graphics
{
	public class TestRenderer : Engine.Modifier
	{
		DefaultShader shader;

		VertexArray<PositionNormalTexture> va;
		
		public void Initialize()
		{
			shader = new DefaultShader(PositionNormalTexture.Descriptor);
			GL.BindFragDataLocation(shader.Handle, 0, "ColorOut");
			shader.CompileAndLink();
			shader.MakeCurrent();
			shader.Projection.Value = Matrix4.CreateOrthographic(4, 4, -4, 4);
			shader.Model.Value = Parent.AbsoluteTransform;
			shader.NormalMatrix.Value = Matrix4.Identity;
			shader.View.Value = Matrix4.Identity;
			shader.ModelViewProjection.Value = shader.Projection.Value;
			
			va = new VertexArray<PositionNormalTexture>();
			
			va.Buffer.Allocate(GenerateVertices(99));
			va.Buffer.BufferData(BufferUsageHint.StaticDraw);
			
		}
		
		public void Draw()
		{
			
			shader.MakeCurrent();
			shader.Projection.Value = Scene.Owner.CurrentCamera.Projection;
			shader.View.Value = Scene.Owner.CurrentCamera.AbsoluteTransform;
			shader.Model.Value = (Parent as Transform).AbsoluteTransform;
			shader.ModelViewProjection.Value = shader.Model.Value * shader.Projection.Value;
			var norm = shader.Model.Value * shader.View.Value;
			norm.Invert();
			norm.Transpose();			
			shader.NormalMatrix.Value = norm;
			
			GL.DrawArrays(BeginMode.Triangles, 0, va.Buffer.Count);
		}
	
		private static readonly Random rnd=new Random();
		public static IEnumerable<PositionNormalTexture> GenerateVertices(int count)
		{
			List<PositionNormalTexture> pos = new List<PositionNormalTexture>();
			
			for(int i = 0; i < count; i++)
			{
				pos.Add(new PositionNormalTexture()
				{
					Pos = new Vector3((float)rnd.NextDouble() * 2 - 1, (float)rnd.NextDouble() * 2 - 1, (float)rnd.NextDouble() * 2 - 1),
					Normal = new Vector3(1, 1, 1),
					TexCoord = new Vector2(1, 1)
				});
			}
			for(int i = 0; i < count; i+=3)
			{
				var va = pos[i+1].Pos - pos[i].Pos;
				var vb = pos[i+2].Pos - pos[i].Pos;
				var norm = Vector3.Cross(va, vb);
				norm.Normalize();
				for(int j = 0; j < 3; j++)
				{
					pos[i] = new PositionNormalTexture()
					{
						Pos = pos[i].Pos,
						Normal = norm
					};
				}
			}
			return pos;
		}			
	}
}

